The Canvas Elements

In HTML 5, a canvas is a rectangle drown on a Web page where you can draw an object, such as 2D shapes or graphics, with the use of JavaScript. It also helps in creating images, visuals, graphs, and photos compositions on a Web page. Another functionality of canvas is to add visual effects to the graphics, such as animation, and make the interface more interactive. For example, you can draw a rectangle to create a region and scoreboard for a game.

Let’s do the following steps to draw shapes on a Web page using the canvas element:

Open a blank Notepad document.

Add the code, below given to the document:


<!DOCTYPE html>
<html>
    <head>
        <title> Using Canvas Element </title>
        <script type="text/javascript" src="../excanvas.js"> </script>
        <script type="text/javascript"> 
            function drow(){
                var canvas = document.getElementById("canvas");
                var ctx = canvas.getContext("2d");
                ctx.fillStyle = "rgb(200,0,0)";
                ctx.fillRect (10,10,55,50);
                
                ctx.fillStyle = "rgb(0,0,200,0.5)";
                ctx.fillRect (35,35,65,50);

                ctx.fillStyle = "rgb(100,0,200,0.5)";
                ctx.fillRect (55,65,85,50);
                }
        </script>
    </head>
<body onload="draw()">
    <div align="center">
        <h3>Showing an Example of Canvas</h3>
        <h4>Rectangle Shape</h4>
        <canvas id="canvas" width="300" height="300"></canvas>
    </div>

</body>
</html> 

Save the document with the name CanvasExample.html

Open the HTML document in the Opera Web browser. The output is shown in below snapshot:

Canvas Example

Note: the canvas element is not supported in Internet Explorer; therefore, we have used Opera Web browser.

Let’s now learn about the new form elements in HTML 5 go through Next Button